/*
 * Copyright (c) 2001 Fabrice Bellard
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * @file
 * audio encoding with libavcodec API example.
 *
 * @example encode_audio.c
 */

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

#include <libavcodec/avcodec.h>

#include <libavutil/channel_layout.h>
#include <libavutil/common.h>
#include <libavutil/frame.h>
#include <libavutil/samplefmt.h>

//AVSampleFormat： https://blog.csdn.net/lyy901135/article/details/103061967
/* check that a given sample format is supported by the encoder */
static int check_sample_fmt(const AVCodec *codec, enum AVSampleFormat sample_fmt)
{
    // 支持的采样格式数组，为空，或者以-1结尾
    const enum AVSampleFormat *p = codec->sample_fmts;
    //判断设置的采样格式是否支持，1 支持 0 不支持
    while (*p != AV_SAMPLE_FMT_NONE) {
        if (*p == sample_fmt)
            return 1;
        p++;
    }
    return 0;
}

/* just pick the highest supported samplerate */
//找到最匹配 编码器支持的采样率最接近的值 supported_samplerates
static int select_sample_rate(const AVCodec *codec)
{
    const int *p;
    int best_samplerate = 0;
    //supported_samplerates 保存了支持的采样率的数组，为空，或者以 0 结尾
    if (!codec->supported_samplerates) //为空，返回44100
        return 44100;

    p = codec->supported_samplerates;
    while (*p) { //找到支持的采样率的最大值
        if (!best_samplerate || abs(44100 - *p) < abs(44100 - best_samplerate))
            best_samplerate = *p;
        p++;
    }
    return best_samplerate;
}

/* select layout with the highest channel count */
//找到编码器最高的通道数
static int select_channel_layout(const AVCodec *codec)
{
    const uint64_t *p;
    uint64_t best_ch_layout = 0;
    int best_nb_channels   = 0;
    //channel_layouts 保存了支持的所有声道布局数组，为空，或者以 0 结尾
    if (!codec->channel_layouts) //为空，返回AV_CH_LAYOUT_STEREO
        return AV_CH_LAYOUT_STEREO;

     //找声道数最多的那个
    p = codec->channel_layouts;
    while (*p) {
        int nb_channels = av_get_channel_layout_nb_channels(*p);

        if (nb_channels > best_nb_channels) {
            best_ch_layout    = *p;
            best_nb_channels = nb_channels;
        }
        p++;
    }
    return best_ch_layout;
}

static void encode(AVCodecContext *ctx, AVFrame *frame, AVPacket *pkt,
                   FILE *output)
{
    int ret;

    /* send the frame for encoding */
    //给编码器送frame
    //原生数据送入编码器,得到packet,如果 frame传null.就会flush 编码器中遗留的数据.所以最后总要才传个null进来
    ret = avcodec_send_frame(ctx, frame);
    if (ret < 0) {
        fprintf(stderr, "Error sending the frame to the encoder\n");
        exit(1);
    }

    /* read all the available output packets (in general there may be any
     * number of them */
    while (ret >= 0) {
        //从编码器中读pkt，pkt里面保存了编码后的数据,然后写到文件
        ret = avcodec_receive_packet(ctx, pkt); //frame->ctx->pkt
        //EAGAIN编码器还需要更多的frame才能继续输出pkt
        //AVERROR_EOF编码器没有更多数据可以读取了，例如被冲洗了
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
            return;
        else if (ret < 0) {
            fprintf(stderr, "Error encoding audio frame\n");
            exit(1);
        }
        //写入文件
        fwrite(pkt->data, 1, pkt->size, output);
        //释放packet，以便后面再次写入
        av_packet_unref(pkt);
    }
}
/*
 * 编码音频  随机生成音频文件.组成frame.送如编码器编码后生成packet.写入文件
 * @param argc
 * @param argv
 * @return
 * avcodec_find_encoder：根据指定的AVCodecID查找注册的解码器。
avcodec_alloc_context3：为AVCodecContext分配内存。
avcodec_open2：打开解码器。
avcodec_send_frame：将AVFrame非压缩数据给编码器。详细介绍见FFmpeg音频解码的编解码API介绍部分。
avcodec_receive_packet：获取到编码后的AVPacket数据。
av_frame_get_buffer: 为音频或视频数据分配新的buffer。在调用这个函数之前，必须在AVFame上设置好以下属性：format(视频为像素格式，音频为样本格式)、nb_samples(样本个数，针对音频)、channel_layout(通道类型，针对音频)、width/height(宽高，针对视频）。
av_frame_make_writable：确保AVFrame是可写的，尽可能避免数据的复制。
如果AVFrame不是是可写的，将分配新的buffer和复制数据。
链接：https://www.jianshu.com/p/c6154e106b8c
 */
int main(int argc, char **argv)
{
    const char *filename;
    const AVCodec *codec;
    AVCodecContext *c= NULL;
    AVFrame *frame;
    AVPacket *pkt;
    int i, j, k, ret;
    FILE *f;
    uint16_t *samples;
    float t, tincr;

    if (argc <= 1) {
        fprintf(stderr, "Usage: %s <output file>\n", argv[0]);
        return 0;
    }
    filename = argv[1];

    /* find the MP2 encoder */
    //查找音视频编码器
    codec = avcodec_find_encoder(AV_CODEC_ID_MP2);
    if (!codec) {
        fprintf(stderr, "Codec not found\n");
        exit(1);
    }

    c = avcodec_alloc_context3(codec); //分配音视频器上下文
    if (!c) {
        fprintf(stderr, "Could not allocate audio codec context\n");
        exit(1);
    }

    /* put sample parameters */
    //设置码率
    c->bit_rate = 64000;

    /* check that the encoder supports s16 pcm input */
    //采样位数16位
    c->sample_fmt = AV_SAMPLE_FMT_S16;
    //检查编码器是否支持该采样位数
    if (!check_sample_fmt(codec, c->sample_fmt)) {
        fprintf(stderr, "Encoder does not support sample format %s",
                av_get_sample_fmt_name(c->sample_fmt));
        exit(1);
    }

    /* select other audio parameters supported by the encoder */
    c->sample_rate    = select_sample_rate(codec); //找到最佳采样率.向上靠拢
    c->channel_layout = select_channel_layout(codec); //找到最高的channel_layout
    c->channels       = av_get_channel_layout_nb_channels(c->channel_layout); //找到最多的通道,根据channel_layout

    /* open it */
    //Initialize the AVCodecContext to use the given AVCodec.
    //打开编码器 初始化编码器上下文
    if (avcodec_open2(c, codec, NULL) < 0) {
        fprintf(stderr, "Could not open codec\n");
        exit(1);
    }
    //打开文件
    f = fopen(filename, "wb");
    if (!f) {
        fprintf(stderr, "Could not open %s\n", filename);
        exit(1);
    }

    /* packet for holding encoded output */
    //初始化packet
    pkt = av_packet_alloc(); //Allocate an AVPacket and set its fields to default values.
    if (!pkt) {
        fprintf(stderr, "could not allocate the packet\n");
        exit(1);
    }

    /* frame containing input raw audio */
    //初始化frame
    frame = av_frame_alloc(); //Allocate an AVFrame and set its fields to default values.
    if (!frame) {
        fprintf(stderr, "Could not allocate audio frame\n");
        exit(1);
    }
    //用编码器上下文给frame设置参数,因为编码是把原始数据转为压缩数据.所以这些参数都是有用户指定的.
    frame->nb_samples     = c->frame_size; //每个声道有多少个采样
    frame->format         = c->sample_fmt; //采样的格式
    frame->channel_layout = c->channel_layout; //声道布局

    /* allocate the data buffers */
    //给frame内部分配内存
    ret = av_frame_get_buffer(frame, 0); //Allocate new buffer(s) for audio or video data.
    if (ret < 0) {
        fprintf(stderr, "Could not allocate audio data buffers\n");
        exit(1);
    }

    /* encode a single tone sound */
    //给frame填充数据，编码，写入文件
    t = 0;
    tincr = 2 * M_PI * 440.0 / c->sample_rate;
    for (i = 0; i < 200; i++) {
        /* make sure the frame is writable -- makes a copy if the encoder
         * kept a reference internally */
        //确定frame是可写的，如果frame被编码器内部引用，会变成不可写，调用此方法，给frame内部的buf指向新分配的空间，使其变为可写
        ret = av_frame_make_writable(frame);
        if (ret < 0)
            exit(1);
        //获得写入的指针，由于设置的是AV_SAMPLE_FMT_S16，非平面类型，data[0]保存了写入地址
        samples = (uint16_t*)frame->data[0];

        for (j = 0; j < c->frame_size; j++) {
            samples[2*j] = (int)(sin(t) * 10000);
            //多个声道，交错写数据
            for (k = 1; k < c->channels; k++)
                samples[2*j + k] = samples[2*j];
            t += tincr;
        }
        //编码，写文件
        encode(c, frame, pkt, f);
    }

    /* flush the encoder */
    // 冲洗编码器，读出剩余数据，写入文件
    encode(c, NULL, pkt, f); //编码
    //关闭文件
    fclose(f);
    //释放资源
    av_frame_free(&frame);
    av_packet_free(&pkt);
    avcodec_free_context(&c);

    return 0;
}
